import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/dashboard',
      name: 'Dashboard',
      component: () => import('@/views/Dashboard.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'Home',
          component: () => import('@/views/Home.vue')
        },
        {
          path: 'users',
          name: 'UserManagement',
          component: () => import('@/views/UserManagement.vue')
        },
        {
          path: 'roles',
          name: 'RoleManagement',
          component: () => import('@/views/RoleManagement.vue')
        },
        {
          path: 'faces',
          name: 'FaceManagement',
          component: () => import('@/views/FaceManagement.vue')
        },
        {
          path: 'work-clothes',
          name: 'WorkClothesManagement',
          component: () => import('@/views/WorkClothesManagement.vue')
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/dashboard'
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态
  authStore.initAuth()
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isAuthenticated) {
      // 未认证，重定向到登录页
      next('/login')
      return
    }
    
    // 额外的权限检查：确保用户有管理员权限
    if (authStore.user && authStore.user.role) {
      const userRole = authStore.user.role
      if (userRole !== 'Admin' && userRole !== 'Administrator' && userRole !== '管理员') {
        // 权限不足，清除登录状态并重定向到登录页
        authStore.logout()
        next('/login')
        return
      }
    }
  } else {
    // 如果已经登录，访问登录页时重定向到仪表板
    if (to.path === '/login' && authStore.isAuthenticated) {
      next('/dashboard')
      return
    }
  }
  
  next()
})

export default router
